package com.dwyinyuan.producer;

import com.dwyinyuan.utils.HttpUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.concurrent.BlockingQueue;

// https://www.tujigu.com/s/35/
public class TujiguProducer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public TujiguProducer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }


    @Override
    public void run() {
        try {
            HttpUtils instance = HttpUtils.getInstance();

            Document document = instance.getHtmlPageResponseAsDocument("https://www.tujigu.com/s/35/");
            Elements elements = document.getElementsByClass("hezi").first()
                    .getElementsByTag("a");

            for (Element element : elements) {
                String href = element.attr("href");
                //加载缓慢
                Document detail_doc = instance.getHtmlPageResponseAsDocument(href);
                Elements contents = detail_doc.getElementsByClass("content");
                if (contents == null || contents.size() <= 0) {
                    continue;
                }
                Element content = contents.first();
                Elements es = content.getElementsByClass("tupian_img");
                if (es == null || es.size() <= 0) {
                    continue;
                }
                for (Element e : es) {
                    String url = e.attr("original");
                    blockingQueue.put(url);
                }
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
